<?php
/**
 * Created by PhpStorm.
 * User: Lizhi
 * Date: 2019/3/28
 * Time: 11:23
 */
namespace APP\Libraries;

class Test
{
    public static function indexs($file)
    {
        $ftpService = env('ftp_Service');//地址
        $ftpUserName = env('ftp_UserName');//账户
        $ftpPwd = env('ftp_Pwd');//密码
        $connect = ftp_connect($ftpService) or die('连接失败');//连接测试

        if ($connect=='连接失败'){
            return [
                "code" => "20001",
                "errorMessages" => "图片服务器连接异常！",
            ];
        }

        if (!$file->isValid()) {
            return [
                "code" => "20001",
                "errorMessages" => "上传错误！",
            ];
        }

        $ext = $file->guessExtension();      // 扩展名
        if (false === stripos('jpeg,jpg,png', $ext)) {//判断是图片格式（jpeg,jpg,png）
            return [
                "code" => "20001",
                "errorMessages" => "上传类型错误，请选择jpeg,jpg,png文件上传！",
            ];
        }

        $size = $file->getClientSize() / 1024 / 1024; //换成m
        if ($size > 5) {//判断图片大小，5M以内
            return [
                "code" => "20001",
                "errorMessages" => "单个文件最大允许上传5M",
            ];
        }

        ftp_login($connect, $ftpUserName, $ftpPwd);//连接登录

        if (!ftp_size($connect,"/image")){
            ftp_mkdir($connect, '/image');//新建文件夹
        }

//        $list = ftp_nlist($connect, "/");//取出目录
//        if (!in_array("/image", $list)) {//判断是否存在
//            ftp_mkdir($connect, '/image');//新建文件夹
//        }

        $str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $len = strlen($str) - 1;
        $randstr = '';
        for ($i = 0; $i < 6; $i++) {
            $num = mt_rand(0, $len);
            $randstr .= $str[$num];
        }

        $newFileName = '/image/' . date('YmdHis') . $randstr . '.' . $ext;//名称：image+时间戳+随机数6位
        $a = ftp_put($connect, $newFileName, $_FILES['file']['tmp_name'], FTP_BINARY, 0);//上传
        if ($a == true) {
            ftp_close($connect);//关闭连接
            return $newFileName;//返回全路径
        }
    }
}